package com.cy.milktea.utils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分页工具类
 */
public class PageHelperUtils {

    /**
     * 存储页面信息的内部类
     * @param <E>
     */
    public static class PageInfo<E> {

        private int page;  //------>页数
        private int pageSize;  //-->每页大小
        private int total;  //----->总数据
        private List<E> list;  //-->储存数据的列表

        public int getPage() {
            return page;
        }

        public void setPage(int page) {
            this.page = page;
        }

        public int getPageSize() {
            return pageSize;
        }

        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }

        public int getTotal() {
            return total;
        }

        public void setTotal(int total) {
            this.total = total;
        }

        public List<E> getList() {
            return list;
        }

        public void setList(List<E> list) {
            this.list = list;
        }
    }

    /**
     * 获取页数和每页大小
     *
     * @param <E>
     * @return
     */
    private static <E> PageInfo<E> getPageAndPageSize() {
        HttpServletRequest request = ServletUtils.getHttpRequest();
        String pageStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("pageSize");

        PageInfo<E> pageInfo = new PageInfo<>();
        pageInfo.page = pageStr == null ? 1 : Integer.parseInt(pageStr);
        pageInfo.pageSize = pageSizeStr == null ? 10 : Integer.parseInt(pageSizeStr);
        return pageInfo;
    }

    /**
     * 封装PageHelper插件分页方法
     *
     * @param <E>
     * @return
     */
    public static <E> Page<E> startPage() {

        PageInfo<E> pageInfo = getPageAndPageSize();
        return PageHelper.startPage(pageInfo.page, pageInfo.pageSize);
    }

    /**
     * 自定义的分页方法
     *
     * @param list 数据源
     * @param <E>
     * @return
     */
    public static <E> PageInfo<E> startPage(List<E> list) {

        PageInfo<E> pageInfo = getPageAndPageSize();
        pageInfo.total = list.size();
        int skipNum = (pageInfo.page - 1) * pageInfo.pageSize;
        //分页
        pageInfo.list = list.stream().skip(skipNum).limit(pageInfo.pageSize).collect(Collectors.toList());
        return pageInfo;
    }

}
